# 引入必要的库
import numpy as np

import yaml
import os
import time
from keras.applications.vgg16 import VGG16, preprocess_input
from keras.preprocessing import image
from joblib import dump as dp, load as ld
import torchvision.transforms as transforms
import torch.nn as nn

# 初始化VGG16模型
model = VGG16(weights='imagenet', include_top=False)

yaml_file_path = '0_setting.yaml'


def get(key):
    with open(yaml_file_path, 'r', encoding='utf-8') as file:
        data = yaml.safe_load(file)
        value = data.get(key, None)
        return value


# 获取 0_setting.yaml 中的键 key 对应的值 value


def preprocess_image_vgg(file_name):
    # 1. 使用keras内置的读图程序，以224x224的尺寸读取图像文件，结果为一个PIL图像对象
    img = image.load_img(file_name, target_size=(224, 224))
    # 2. 将PIL图像对象转换为NumPy数组
    img = image.img_to_array(img)
    # 3. 把单幅图像放到一个数组中，提供批次信息
    x = np.expand_dims(img, axis=0)
    # 4. 使用VGG16模型的预处理函数对图像进行预处理
    x = preprocess_input(x)
    # 5. 使用VGG16模型对图像进行特征提取
    features = model.predict(x, verbose=0)
    # 6. 将提取的特征展平为一维数组
    features_flattened = features.flatten()
    return features_flattened


# 用joblib把叫做 name 的对象 obj 保存(序列化)到位置 loc
def dump(obj, name, loc):
    start = time.time()
    print(f"把{name}保存到{loc}")
    dp(obj, loc)
    end = time.time()
    print(f"保存完毕,文件位置:{loc}, 大小:{os.path.getsize(loc) / 1024 / 1024:.3f}M")
    print(f"运行时间:{end - start:.3f}秒")


# 用joblib读取(反序列化)位置loc的对象obj,对象名为name
def load(name, loc):
    print(f"从{loc}提取文件{name}")
    obj = ld(loc)
    return obj
